//
//  ViewController.m
//  MapViewTest
//
//  Created by 美鑫科技 on 16/5/10.
//  Copyright © 2016年 MorpLCP. All rights reserved.
//

#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "CustomImage.h"
#import "MapCenterView.h"

@interface ViewController ()<MKMapViewDelegate>

@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, strong) MapCenterView *mapCenterView;
@property (nonatomic, strong) CLGeocoder *geoCoder;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.mapView = [[MKMapView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.mapView.delegate = self;
    [self.view addSubview:self.mapView];
    self.geoCoder = [CLGeocoder new];
    [self addCenterView];
}

- (void)addCenterView{
    UIImage *image = [CustomImage imageNamed:@"didianz@2x"];
    self.mapCenterView = [[MapCenterView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    self.mapCenterView.center = CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0 - 5);
    self.mapCenterView.bacImage = image;
    self.mapCenterView.backgroundColor = [UIColor clearColor];
    self.mapCenterView.title = @"***";
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.mapCenterView showCalloutView];
    });
    [self.view addSubview:self.mapCenterView];
}

#pragma mark --MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    CLLocationCoordinate2D cllocation = [self.mapView convertPoint:self.mapCenterView.center toCoordinateFromView:self.view];
    [self getAddressByLatitude:cllocation.latitude longitude:cllocation.longitude];
    [self.mapCenterView insert];
    [self.mapCenterView showCalloutView];
}

- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{
    self.mapCenterView.title = nil;
    [self.mapCenterView pullout];
    [self.mapCenterView dismissCalloutView];
}

#pragma mark 根据坐标取得地名
- (void)getAddressByLatitude : (CLLocationDegrees)latitude longitude : (CLLocationDegrees)longitude{
    CLLocation *location = [[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    [_geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        //获取地标
        CLPlacemark *placemark = [placemarks firstObject];
        self.mapCenterView.title = placemark.addressDictionary[@"Name"];
        NSLog(@"%@",placemark.addressDictionary[@"Name"]);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
